package com.post799.soundapp;

import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONObject;

import com.bappi.utils.Constants;
import com.bappi.utils.Utils;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.IBinder;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import android.util.Log;

public class SoundPlayerService extends Service implements
		MediaPlayer.OnPreparedListener {

	private static String KEY_MEDIA_PLAYER_COMMAND = "KEY_MEDIA_PLAYER_COMMAND_1";
	private static String KEY_COMMAND = "KEY_COMMAND";
	private static String KEY_VALUE = "KEY_VALUE";
	private static String KEY_TIME = "KEY_TIME";
	private static int COMMAND_PLAY = 0;
	private static int COMMAND_PAUSE = 1;
	private static int COMMAND_VOLUME = 3;

	private MediaPlayer mediaPlayer;
	private String fileName;
	private int volume;
	private int duration;
	private boolean looping;

	private SharedPreferences sharedPreferences;

	public static void play(SharedPreferences sp) {
		try {
			JSONObject jo = new JSONObject();
			jo.put(KEY_TIME, System.currentTimeMillis());
			jo.put(KEY_COMMAND, COMMAND_PLAY);
			sp.edit().putString(KEY_MEDIA_PLAYER_COMMAND, jo.toString())
					.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void pause(SharedPreferences sp) {
		try {
			JSONObject jo = new JSONObject();
			jo.put(KEY_TIME, System.currentTimeMillis());
			jo.put(KEY_COMMAND, COMMAND_PAUSE);
			sp.edit().putString(KEY_MEDIA_PLAYER_COMMAND, jo.toString())
					.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void setVolume(SharedPreferences sp, int val) {
		try {
			JSONObject jo = new JSONObject();
			jo.put(KEY_TIME, System.currentTimeMillis());
			jo.put(KEY_COMMAND, COMMAND_VOLUME);
			jo.put(KEY_VALUE, val);
			sp.edit().putString(KEY_MEDIA_PLAYER_COMMAND, jo.toString())
					.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private OnSharedPreferenceChangeListener ospcl = new OnSharedPreferenceChangeListener() {

		public void onSharedPreferenceChanged(final SharedPreferences sp,
				String key) {
			try {
				if (KEY_MEDIA_PLAYER_COMMAND.equals(key)) {
					String object = sp
							.getString(KEY_MEDIA_PLAYER_COMMAND, null);
					if (object != null) {
						JSONObject jo = new JSONObject(object);
						int command = jo.getInt(KEY_COMMAND);
						if (command == COMMAND_PLAY) {
							mediaPlayer.start();
							if (looping) {
								shcedule();
							}
						} else if (command == COMMAND_PAUSE) {
							mediaPlayer.pause();
						} else if (command == COMMAND_VOLUME) {
							volume = jo.getInt(KEY_VALUE);
							float val = volume / 100.0F;
							mediaPlayer.setVolume(val, val);
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	private OnCompletionListener onCompletionListener = new OnCompletionListener() {
		@Override
		public void onCompletion(MediaPlayer arg0) {
			try {
				Tab1Activity1.notifyMediaCompleted(sharedPreferences);
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
	};

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public void onStart(Intent intent, int startId) {
		try {
			super.onStart(intent, startId);
			sharedPreferences = PreferenceManager
					.getDefaultSharedPreferences(this);
			fileName = intent.getStringExtra(Constants.KEY_AUDIO_FILE_NAME);
			sharedPreferences.registerOnSharedPreferenceChangeListener(ospcl);
			mediaPlayer = MediaPlayer.create(this,
					Utils.getResourceID(fileName, "raw", this));
			mediaPlayer.setWakeMode(getApplicationContext(),
					PowerManager.PARTIAL_WAKE_LOCK);
			mediaPlayer.setOnCompletionListener(onCompletionListener);

			volume = intent.getIntExtra(Constants.KEY_AUDIO_VOLUME, 50);
			float val = volume / 100.0F;
			mediaPlayer.setVolume(val, val);
			looping = intent.getBooleanExtra(
					Constants.KEY_AUDIO_SHOULD_LOOPING, false);
			mediaPlayer.setLooping(looping);
			if (intent.getBooleanExtra(Constants.KEY_AUDIO_SHOULD_PLAY, true)) {
				mediaPlayer.start();
			}
			duration = intent.getIntExtra(Constants.KEY_AUDIO_LOOPING_TIME, 0);
			if (looping) {
				shcedule();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void shcedule() {
		try {
			final Timer timer = new Timer();
			final TimerTask timerTask = new TimerTask() {
				@Override
				public void run() {
					try {
						if (mediaPlayer != null) {
							Log.i("DREG", "IN TASK");
							Tab1Activity1
							.notifyMediaCompleted(sharedPreferences);
							timer.cancel();
							cancel();
							mediaPlayer.pause();
							
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			};
			timer.schedule(timerTask, duration);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onPrepared(MediaPlayer mp) {

	}

	@Override
	public void onDestroy() {
		try {
			if (mediaPlayer != null) {
				mediaPlayer.stop();
				mediaPlayer.release();
				mediaPlayer = null;
			}
			if (sharedPreferences != null && ospcl != null) {
				sharedPreferences
						.unregisterOnSharedPreferenceChangeListener(ospcl);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		super.onDestroy();
	}
}
